import {
  AppstoreOutlined,
  HomeOutlined,
  SettingOutlined,
  UserOutlined,
} from '@ant-design/icons';
import ProLayout, { BasicLayoutProps } from '@ant-design/pro-layout';
import { Avatar } from 'antd';
import React, { useEffect, useState } from 'react';
import { Link, useHistory, useLocation } from 'react-router-dom';

import UserModel from '@/models/user';
import { getToken } from '@/utils/cookies';

const NestLayout: React.FC<BasicLayoutProps> = (props) => {
  const { pathname } = useLocation();
  const history = useHistory();
  const { menus } = UserModel();

  const [subMenus, setSubMenus] = useState([]);

  const loginPath = '/login';

  useEffect(() => {
    menus.map((v: any) => {
      if (v.path === pathname) {
        setSubMenus(v.children);
      }
    });
  }, [pathname]);

  return (
    <div style={{ height: '100vh' }}>
      <ProLayout
        collapsedButtonRender={false}
        collapsed
        iconfontUrl="//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js"
        onPageChange={() => {
          const hasToken = getToken();
          if (!hasToken && pathname !== loginPath) {
            history.push(loginPath);
          }
        }}
        route={{
          routes: [
            {
              name: '首页',
              path: '/home',
              code: 'HOME',
              icon: <HomeOutlined />,
              id: '1',
              parentId: null,
            },
            {
              name: '工作台',
              path: '/dashboard',
              code: 'DASHBOARD',
              icon: <AppstoreOutlined />,
              id: '2',
              parentId: null,
            },
            {
              name: '系统管理',
              path: '/system',
              code: 'SYSTEM',
              icon: <SettingOutlined />,
              id: '3',
              parentId: null,
            },
          ],
        }}
        menuItemRender={(item, dom) => {
          if (!item.path || location.pathname === item.path) {
            return dom;
          }
          return <Link to={item.path}>{dom}</Link>;
        }}
        headerRender={false}
        disableContentMargin>
        {subMenus.length > 0 ? (
          <ProLayout
            menuHeaderRender={false}
            navTheme="light"
            route={{ routes: subMenus }}
            rightContentRender={() => (
              <div>
                <Avatar shape="square" size="small" icon={<UserOutlined />} />
              </div>
            )}
            menuItemRender={(item, dom) => {
              if (!item.path || location.pathname === item.path) {
                return dom;
              }
              return <Link to={item.path}>{dom}</Link>;
            }}>
            {props.children}
          </ProLayout>
        ) : (
          <>{props.children}</>
        )}
      </ProLayout>
    </div>
  );
};

export default NestLayout;
